
package cn.platform.service.impl;

import cn.platform.entity.StuHomework;
import cn.platform.entity.Student;
import cn.platform.entity.Teacher;
import cn.platform.mapper.*;
import cn.platform.request.StuHomework.StuHomeworkQueryDTO;
import cn.platform.request.StuHomework.StuHomeworkUpdateDTO;
import cn.platform.response.PageResult;
import cn.platform.response.StuHomeworkVO;
import cn.platform.service.StuHomeworkService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Year;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StuHomeworkServiceImpl implements StuHomeworkService {

    @Autowired
    private StuHomeworkMapper stuHomeworkMapper;
    @Autowired
    private TeacherMapper1 teacherMapper1;

    @Autowired
    private ClazzMapper1 clazzMapper1;

    @Autowired
    private StudentMapper1 studentMapper1;


    /**
     * 根据条件分页查询活动信息
     * @return
     * @author
     */
    @Override

    public PageResult<StuHomeworkVO> page(StuHomeworkQueryDTO stuHomeworkQueryDTO) {

        if (stuHomeworkQueryDTO.getGrade()!=null&&stuHomeworkQueryDTO.getGrade() > 0){
            int currentYear = Year.now().getValue();
            stuHomeworkQueryDTO.setGradeYear(currentYear-stuHomeworkQueryDTO.getGrade()+1);
        }

        PageHelper.startPage(stuHomeworkQueryDTO.getPage(),stuHomeworkQueryDTO.getPageSize());

        Map<String,Object> map = new HashMap<>();
        if (stuHomeworkQueryDTO.getTitle()!=null && !stuHomeworkQueryDTO.getTitle().isEmpty()){
            map.put("title",stuHomeworkQueryDTO.getTitle());
        }else {
            map.put("title",null);
        }
        if(stuHomeworkQueryDTO.getPublisher()!=null && !stuHomeworkQueryDTO.getPublisher().isEmpty()){
            map.put("publisher",stuHomeworkQueryDTO.getPublisher());
        }else {
            map.put("publisher",null);
        }
        stuHomeworkQueryDTO.setType("作业");//后续实现
        map.put("type",stuHomeworkQueryDTO.getType());
        if(stuHomeworkQueryDTO.getStartTime()!=null){
            map.put("startTime", LocalDateTime.of(stuHomeworkQueryDTO.getStartTime(), LocalTime.MIN));
        }else {
            map.put("startTime",null);
        }
        if(stuHomeworkQueryDTO.getEndTime()!=null){
            map.put("endTime",LocalDateTime.of(stuHomeworkQueryDTO.getEndTime(), LocalTime.MAX));
        }else {
            map.put("endTime",null);
        }
        if(stuHomeworkQueryDTO.getGradeYear()!=null){
            map.put("gradeYear", stuHomeworkQueryDTO.getGradeYear());
        }
        if(stuHomeworkQueryDTO.getClassNum()!=null){
            map.put("classNum",stuHomeworkQueryDTO.getClassNum());
        }
        List<StuHomeworkVO> voList =stuHomeworkMapper.pageQuery(map);

        int currentYear = Year.now().getValue();
        for(StuHomeworkVO vo:voList){
            int gradeNum = currentYear-vo.getGradeYear()+1;
            if (gradeNum>=1 && gradeNum<=6){
                vo.setGrade(gradeNum);
            }else {
                vo.setGrade(null);
                vo.setClassNum(null);
            }
        }

        Page<StuHomeworkVO> page =(Page<StuHomeworkVO>) voList;

        return new PageResult<>(page.getTotal(), page.getResult());
    }

    /**
     * 查看活动详情
     * @param id
     * @return
     */

    public StuHomeworkVO detail(String id) {
        StuHomework stuHomework=stuHomeworkMapper.getById(id);


        String publisher = null;
        publisher=teacherMapper1.getNameById(stuHomework.getPubId());
        String classNum=null;
        classNum= clazzMapper1.getClassNumById(stuHomework.getClassId());//后续实现
        int currentYear = Year.now().getValue();
        int grade = currentYear- clazzMapper1.getGradeYearById(stuHomework.getClassId())+1;

        StuHomeworkVO stuHomeworkVO=new StuHomeworkVO();

        BeanUtils.copyProperties(stuHomework,stuHomeworkVO);


        LocalDateTime pubTime = stuHomework.getPubTime().toLocalDate().atStartOfDay();
        LocalDateTime updateTime = stuHomework.getUpdateTime().toLocalDate().atStartOfDay();
        stuHomeworkVO.setPubTime(pubTime);
        stuHomeworkVO.setUpdateTime(updateTime);



       stuHomeworkVO.setPublisher(publisher);
        stuHomeworkVO.setClassNum(classNum);
        stuHomeworkVO.setGrade(grade);


        return stuHomeworkVO;
    }


    @Override
    @Transactional

    public void save(StuHomework stuHomework) {
        // 设置发布时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        stuHomework.setPubTime(now);
        stuHomework.setUpdateTime(now);

        stuHomeworkMapper.insertHomework(stuHomework);
        log.info("新增作业成功, ID: {}", stuHomework.getId());
    }



    @Override
    @Transactional
    public void delete(String id) {
        stuHomeworkMapper.deleteById(id);
        log.info("删除作业成功, ID: {}", id);
    }

    @Override
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        stuHomeworkMapper.deleteBatch(ids);

    }



    @Transactional
    public void update(StuHomeworkUpdateDTO dto) {
        // 修改点：添加完整的更新逻辑
        StuHomework homework = stuHomeworkMapper.getById(dto.getId());
        if (homework == null) {
            throw new RuntimeException("作业不存在");
        }

        // 只更新允许修改的字段
        if (dto.getTitle() != null) {
            homework.setTitle(dto.getTitle());
        }
        if (dto.getContent() != null) {
            homework.setContent(dto.getContent());
        }
        homework.setUpdateTime(LocalDateTime.now());

        stuHomeworkMapper.updateHomework(homework);
        log.info("更新作业成功, ID: {}", dto.getId());
    }
    // 新增：获取学生列表
    public List<Map<String, Object>> getStudents(String name) {
        List<Student> students;
        if (name != null && !name.isEmpty()) {
            students = studentMapper1.searchByName(name);
        } else {
            students = studentMapper1.getAll();//后续实现
        }
        return students.stream()
                .map(s -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", s.getId());
                    map.put("name", s.getRealName());
                    return map;
                })
                .collect(Collectors.toList());
    }

    // 新增：获取老师列表
    public List<Map<String, Object>> getTeachers(String name) {
        List<Teacher> teachers;
        if (name != null && !name.isEmpty()) {
            teachers = teacherMapper1.searchByName(name);//后续实现
        } else {
            teachers = teacherMapper1.getAll();//后续实现
        }
        return teachers.stream()
                .map(t -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", t.getId());
                    map.put("name", t.getRealName());
                    return map;
                })
                .collect(Collectors.toList());
    }

//    @Override
//    public Object getStudents(String name) {
//        return null;
//    }
//
//    @Override
//    public Object getTeachers(String name) {
//        return null;
//    }

}

